import 'package:flutter/material.dart';

void main() {
  runApp(const VariableDemoApp());
}

class VariableDemoApp extends StatelessWidget {
  const VariableDemoApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dart 变量特性演示',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const VariableDemoHomePage(),
    );
  }
}

class VariableDemoHomePage extends StatefulWidget {
  const VariableDemoHomePage({super.key});

  @override
  State<VariableDemoHomePage> createState() => _VariableDemoHomePageState();
}

class _VariableDemoHomePageState extends State<VariableDemoHomePage> {
  String _output = '';
  final ScrollController _scrollController = ScrollController();

  // 变量声明示例
  void _showVariableDeclaration() {
    _clearOutput();
    var name = 'Bob';
    Object objName = 'Alice';
    String strName = 'Charlie';

    _log('变量声明示例：');
    _log('var name = $name');
    _log('Object objName = $objName');
    _log('String strName = $strName');
  }

  // 空安全示例
  void _showNullSafety() {
    _clearOutput();
    String? nullableName = null;
    String nonNullableName = 'Default';

    _log('空安全示例：');
    _log('可空变量：nullableName = $nullableName');
    _log('非空变量：nonNullableName = $nonNullableName');

    // 非空断言示例
    nullableName = 'Test';
    _log('非空断言：nullableName!.length = ${nullableName!.length}');
  }

  // 默认值示例
  void _showDefaultValues() {
    _clearOutput();
    int? lineCount;
    String? message;

    _log('默认值示例：');
    _log('int? lineCount = $lineCount');
    _log('String? message = $message');
  }

  // 延迟初始化示例
  void _showLateInitialization() {
    _clearOutput();
    late String description;

    try {
      description = 'Late Initialization Demo';
      _log('延迟初始化：$description');
    } catch (e) {
      _log('错误：$e');
    }
  }

  // final 和 const 示例
  void _showFinalAndConst() {
    _clearOutput();
    final String name = 'Final Name';
    const int constantValue = 100;

    _log('final 变量：name = $name');
    _log('const 常量：constantValue = $constantValue');

    // 尝试修改 final 变量（会报错）
    // name = 'New Name'; // 取消注释会触发错误
  }

  // 通配符变量示例
  void _showWildcardVariables() {
    _clearOutput();
    var _ = 10; // 外部作用域的通配符变量
    List<int> list = [1, 2, 3];

    _log('通配符变量示例：');
    _log('for (var _ in list) 循环执行');
    list.forEach((element) => _log('元素：$element')); // 修改为 element

    try {
      throw Exception('通配符捕获');
    } catch (_) {
      _log('捕获异常：通配符处理');
    }
  }

  // 日志记录方法
  void _log(String message) {
    setState(() {
      _output += '$message\n';
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    });
  }

  // 清空输出
  void _clearOutput() {
    setState(() {
      _output = '';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Dart 变量特性')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // 功能按钮
            ElevatedButton(
              onPressed: _showVariableDeclaration,
              child: const Text('变量声明示例'),
            ),
            ElevatedButton(
              onPressed: _showNullSafety,
              child: const Text('空安全示例'),
            ),
            ElevatedButton(
              onPressed: _showDefaultValues,
              child: const Text('默认值示例'),
            ),
            ElevatedButton(
              onPressed: _showLateInitialization,
              child: const Text('延迟初始化'),
            ),
            ElevatedButton(
              onPressed: _showFinalAndConst,
              child: const Text('final & const'),
            ),
            ElevatedButton(
              onPressed: _showWildcardVariables,
              child: const Text('通配符变量'),
            ),

            // 输出区域
            Expanded(
              child: SingleChildScrollView(
                controller: _scrollController,
                child: Container(
                  margin: const EdgeInsets.only(top: 20),
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey.shade300),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: SelectableText(
                    _output,
                    style: const TextStyle(
                      fontFamily: 'Courier New',
                      fontSize: 12,
                      color: Colors.black87,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
